<?php

class Zgm_Controller_Plugin_FlashMessenger extends Zend_Controller_Plugin_Abstract {

   public function postDispatch(Zend_Controller_Request_Abstract $request) {
      // Initialize FlashMessenger helper and get messages.
      $actionHelperFlashMessenger = new Zend_Controller_Action_Helper_FlashMessenger();
      $messagesSuccess = $actionHelperFlashMessenger->setNamespace('messages')->getMessages();

      // If there're no messages or dispatch process is failed to finish, quit plugin
      if (empty($messagesSuccess) || !$request->isDispatched()) {
         return;
      }
      
      $view = new Zend_View();
      $view->addScriptPath(APPLICATION_PATH.'/views/scripts');
      // Add variable for view scripts
      $view->messages = $messagesSuccess;

      // Set view script with new variable and render it using messages template
      $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
      $viewRenderer->setView($view)
                   ->renderScript('messages.phtml');
   }
}